<div class="modal fade" id="Modal" tabindex="1" role="dialog"
     aria-labelledby="myModalLabel" aria-hidden="true"></div>

<form class="form-horizontal" role="form" id="userSearchForm">
    <div class="row" id="infolinkList-search">
        <div class="col-md-12">
            <div class="panel">
                <header class="panel-heading">
                    查询条件  <span class="tools pull-right"> <a href="javascript:;"
                                                             class="fa fa-chevron-down"></a> </span>
                </header>

                <div class="panel-body">
                    <div class="col-lg-12">
                        <div class="col-lg-4">
                            <div class="form-group">
                                <label class="col-lg-4 col-sm-2 control-label">登录名称</label>
                                <div class="col-lg-8">
                                    <input type="text" id="login-name" name="loginName"
                                           class="form-control required" placeholder=" "/>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-4">
                            <div class="form-group">
                                <label class="col-lg-4 col-sm-2 control-label">真实姓名</label>
                                <div class="col-lg-8">
                                    <input type="text" id="user-nameb" name="userName"
                                           class="form-control required"/>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-4">
                            <div class="form-group">
                                <label class="col-lg-4 col-sm-2 control-label">邮箱地址</label>
                                <div class="col-lg-8">
                                    <input type="text" id="e-mail" name="email"
                                           class="form-control required" placeholder=" "/>
                                </div>
                            </div>
                        </div>
                    </div>


                </div>

            </div>
        </div>
    </div>

    <div class="row" id="infolinkList-sort">
        <div class="col-md-12">
            <div class="panel">
                <header class="panel-heading">
                    排序条件  <span class="tools pull-right"> <a href="javascript:;"
                                                             class="fa fa-chevron-down"></a> </span>
                </header>
                <div class="panel-body ">
                    <div class="col-lg-12">
                        <div class="col-lg-4">
                            <div class="form-group">
                                <label class="col-lg-4 col-sm-2 control-label">首排</label>
                                <div class="col-lg-8">
                                    <select id="first-opt" name="first" onchange=""
                                            class="form-control">
                                        <option value=""></option>
                                        <option value="loginName">登录名称</option>
                                        <option value="userName">真实姓名</option>
                                        <option value="email">邮件地址</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-4">
                            <div class="form-group">
                                <label class="col-lg-4 col-sm-2 control-label">排序</label>
                                <div class="col-lg-8">
                                    <select id="first-sort" name="first" onchange=""
                                            class="form-control">
                                        <option value="ASC">升序</option>
                                        <option value="DESC">降序</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-12">
                        <div class="col-lg-4">
                            <div class="form-group">
                                <label class="col-lg-4 col-sm-2 control-label">次排</label>
                                <div class="col-lg-8">
                                    <select class="form-control" id="second-opt" name="second" onchange="">
                                        <option value=""></option>
                                        <option value="loginName">登录名称</option>
                                        <option value="userName">真实姓名</option>
                                        <option value="email">邮件地址</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-4">
                            <div class="form-group">
                                <label class="col-lg-4 col-sm-2 control-label">排序</label>
                                <div class="col-lg-8">
                                    <select id="second-sort" name="second" onchange=""
                                            class="form-control">
                                        <option value="ASC">升序</option>
                                        <option value="DESC">降序</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="panel-footer">
                    <div class="text-center">
                        <input type="button" id="btn_searcher" value="查询"
                               class="btn btn-primary"/>
                        <input type="reset" id="btn_reset" class="btn btn-reset"/>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

<!-- 搜索面板end -->
<!-- 用户列表面板 start -->
<div class="row" id="infolinkList-div">
    <div class="col-md-12">
        <div class="panel">
            <header class="panel-heading">
                用户列表
            </header>
            <div class="panel-body  right_centent">
                <div class="col-lg-12">
                    <div id="toolbar" class="btn-group">
                        <button id="add-btn" type="button" class="btn btn-default">
                            <span class="fa fa-plus" aria-hidden="true"></span> 新 增
                        </button>

                        <button id="remove-btn" type="button" class="btn btn-default">
                            <span class="fa fa-times" aria-hidden="true"></span> 删 除
                        </button>

                        <button id="import-btn" type="button" class="btn btn-default">
                            <span class="glyphicon glyphicon-import" aria-hidden="true"></span> 导 入
                        </button>

                        <a id="exportSelect" class="btn btn-default"
                           onclick="selectUserExport('selectedId');">
                            <span class="glyphicon glyphicon-export" aria-hidden="true"></span> 批量导出
                        </a>

                        <a id="exportAll" class="btn btn-default"
                           onclick="selectUserExport('allId');">
							<span
                                    class="glyphicon glyphicon-export" aria-hidden="true"></span> 全部导出
                        </a>

                    </div>
                    <table id="userListTable"></table>

                </div>
            </div>
        </div>
    </div>
</div>


<script th:inline="javascript">
    /*<![CDATA[*/
    //页面上显示隐藏
    $('.panel .tools .fa').click(function () {
        var el = $(this).parents(".panel").children(".panel-body");
        if ($(this).hasClass("fa-chevron-down")) {
            $(this).removeClass("fa-chevron-down").addClass("fa-chevron-up");
            el.slideUp(200);
        } else {
            $(this).removeClass("fa-chevron-up").addClass("fa-chevron-down");
            el.slideDown(200);
        }
    });
    //初始化页数
    $('#userListTable').bootstrapTable({
        url: 'sys/user-list',
        method: 'post', //请求方式（*）
        dataType: 'json',
        contentType: "application/x-www-form-urlencoded",
        showExport: true, //是否显示导出按钮
        exportDataType: "all", //basic'导出当前页, 'all'导出全部, 'selected'导出选中项.
        toolbar: '#toolbar', //工具按钮用哪个容器
        undefinedText: "-",//当数据为 undefined 时显示的字符
        striped: true, //是否显示行间隔色
        cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true, //是否显示分页（*）
        pageSize: 5, //每页显示的记录数
        pageNumber: 1, //当前第几页
        pageList: [5, 10, 15, 20, 25], //记录数可选列表
        sortable: false, //是否启用排序
        sortOrder: "asc", //排序方式
        sidePagination: "server", //分页方式：client客户端分页，server服务端分页（*）
        ////查询参数,每次调用是会带上这个参数，可自定义
        queryParams: queryParams,
        search: false, //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
        strictSearch: true,
        showColumns: true, //是否显示所有的列
        showRefresh: true, //是否显示刷新按钮
        minimumCountColumns: 4, //最少允许的列数
        responseHandler: function (res) {
            if (res) {
                return {
                    "rows": res.data.users,
                    "total": res.data.total
                };

            } else {
                return {
                    "rows": [],
                    "total": 0
                };
            }
        },
        //clickToSelect: true,                //是否启用点击选中行
        //height: 600,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
        uniqueId: "id", //每一行的唯一标识，一般为主键列
        showToggle: true, //是否显示详细视图和列表视图的切换按钮
        cardView: false, //是否显示详细视图
        detailView: false, //是否显示父子表
        columns: [
            {
                checkbox: true,
                formatter: function (i, row) {            // 每次加载 checkbox 时判断当前 row 的 id 是否已经存在全局 Set() 里
                    if ($.inArray(row.id, overAllIds) != -1) {// 因为 判断数组里有没有这个 id
                        return {
                            checked: true               // 存在则选中
                        }
                    }
                }
            },
            {
                field: 'id',
                title: 'ID',
                visible: false
            },
            {
                field: 'avatar',
                title: '头像',
                align: 'center',
                formatter: function (value, row, index) {
                    var imgUrl = 'files/' + row.avatar;
                    if (row.avatar == '' || row.avatar == null) {
                        imgUrl = "/images/default.jpg";
                    }
                    return '<img  src=' + imgUrl + ' class="img-rounded"   style="width:50px;height:50px;" >';
                }
            },
            {
                field: 'loginName',
                title: '登录名称'
            },
            {
                field: 'userName',
                title: '真实名称'

            },
            {
                field: 'email',
                title: '邮箱'
            },
            {
                field: 'phoneNum',
                title: '电话'
            },

            {
                title: '操    作',
                field: 'id',
                align: 'center',
                formatter: function (value, row, index) {
                    var id = row.id;
                    var e;
                    e = '<a href ="#" title="编辑"><span class="fa fa-wrench" onclick="editUser(\''
                            + id
                            + '\')"> </span></a>&nbsp;&nbsp;'

                            + '<a href ="#" title="注销"><span class="fa fa-lock" aria-hidden="true" onclick="disableUser(\''
                            + id
                            + '\')"> </span></a>&nbsp;&nbsp;'
                            + '<a href ="#" title="删除"><span class="fa fa-times"  onclick="deleteUser(\''
                            + id
                            + '\')"> </span></a>&nbsp;&nbsp;'
                            + '<a href ="#" title="修改密码"><span class="fa fa-key"  onclick="modifyPassword(\''
                            + id
                            + '\')"> </span></a>&nbsp;&nbsp;'
                            + '<a href ="#"  alt="" title="上传头像"><span  class="fa fa-user"  onclick="uploadAvatar(\''
                            + id + '\')"> </span></a>';
                    return e;
                },
                events: 'operateEvents'
            }]
    });
    //为翻页保留checkbox选中准备
    $('#userListTable').on('uncheck.bs.table check.bs.table check-all.bs.table uncheck-all.bs.table', function (e, rows) {
        var datas = $.isArray(rows) ? rows : [rows];        // 点击时获取选中的行或取消选中的行
        examine(e.type, datas);                              // 保存到全局 Array() 里
    });

    //设置查询条件，把分页，查询条件，排序等信息拼接成一个models字符串对象传递至后台
    function queryParams(params) {
        var search = {};
        $.each($("#userSearchForm").serializeArray(), function (i, field) {
            search[field.name] = field.value;
        });
        var json = {
            'page': this.pageNumber,
            'pageSize': this.pageSize,
            'filter': {
                'filters': [{
                    field: "loginName",
                    value: search.loginName
                }, {
                    field: "userName",
                    value: search.userName
                }, {
                    field: "state",
                    value: "1"
                }, {
                    field: "email",
                    value: search.email
                }]
            },
            'sort': [{
                field: $("#first-opt").val(),
                dir: $("#first-sort").val()
            }, {
                field: $("#second-opt").val(),
                dir: $("#second-sort").val()
            }]
        };
        var baseData = JSON.stringify(json);
        var param = {
            models: baseData
        };

        return param;
    }

    //刷新
    function refreshFunction() {
        $('#userListTable').bootstrapTable('refresh');
    }

    function exp() {
        $('#userListTable').bootstrapTable({showExport: true, exportDataType: "all"})
    }

    //导入excel
    $("#import-btn").click(function () {
        $('#Modal').modal('show');
        $('#Modal').load('sys/user-upload-excel');
    });

    //搜索
    $("#btn_searcher").click(function () {
        var flag = $('#userSearchForm').bootstrapValidator(
                'validate').data('bootstrapValidator')
                .isValid();
        if (flag) {
            refreshFunction();
        }

    });

    //重置表单所有验证规则
    $("#btn_reset").click(function () {
        $('#userSearchForm').data("bootstrapValidator").resetForm();
    });

    //增新用户
    $("#add-btn").click(function () {
        $('#Modal').modal('show');
        $('#Modal').load('sys/user-add');
    });
    //设置密码
    function modifyPassword(id) {
        $('#Modal').modal('show');
        $('#Modal').load('sys/user-modify-pwd?id=' + id + '')

    }
    //编辑用户
    function editUser(obj) {
        $('#Modal').modal('show');
        $('#Modal').load('sys/user-edit?id=' + obj + '');
    }
    //上传头像
    function uploadAvatar(id) {
        $('#Modal').modal('show');
        $('#Modal').load('sys/user-upload-avatar?id=' + id);
    }

    //删除选中的Id集合
    $("#remove-btn").click(function () {
        //被选着集合
        //var jsonSelectedIDs = getSelectionItem();

        var length = overAllIds.length;

        if (length > 0) {
            layer.confirm('您确认删除选中记录？', {
                btn: ['删除'] //按钮
            }, function () {
                //调用删除
                deleteUserBy(overAllIds);
            });
        } else {
            layer.msg("请选择删除项", {
                icon: 2
            });
            return;
        }
    });

    //选择和全部导出 excel
    function selectUserExport(tag) {

        //定义id数组 默认全选
        var token = $("meta[name='_csrf']").attr("content");

        if (tag == 'allId') {
            //数组转json
            var models = "";
            $("#exportAll").prop("href", "sys/user-excel-export-id?models=" + models);

        } else if (tag == 'selectedId') {
            //获取选中的值
            var tempIDs = getSelectionItem();

            if (tempIDs.length == 0) {
                layer.msg("请选择导出项", {icon: 2});
            } else {
                //数组转json
                var models = JSON.stringify(tempIDs);
                $("#exportSelect").prop("href", "sys/user-excel-export-id?models=" + tempIDs.toString());
            }
        }

    }

    //注销用户
    function disableUser(id) {
        var selectedIDs = new Array();
        //默认一个
        selectedIDs[0] = id;
        var models = JSON.stringify(selectedIDs);
        layer.confirm('您确认注销选中记录？', {
                    btn: ['注销'] //按钮
                }, function () {
                    $.ajax({
                        url: 'sys/user-change-state',
                        data: {"models": models, "state": "0"},
                        type: 'post',
                        success: function (data, textStatus, jqXHR) {
                            if (data.error)
                                layer.msg(data.error, {icon: 2});
                            else {
                                layer.msg('注销用户成功', {icon: 1});
                                refreshFunction();
                            }
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                        }
                    });
                }
        );

    }

    //删除用户
    function deleteUser(id) {
        layer.confirm('您确认删除当前记录？', {
            btn: ['删除'] //按钮
        }, function () {
            var selectedIDs = new Array();
            selectedIDs[0] = id;
            deleteUserBy(selectedIDs);
        });

    }

    //执行选项id
    function getSelectionItem() {
        var selections = $('#userListTable').bootstrapTable('getAllSelections');
        //集合ID
        var jsonSelectedIDs = new Array();
        var length = selections.length;
        if (length > 0) {
            $.each(selections, function (index, obj) {
                jsonSelectedIDs.push(obj.id);
            });
        }
        return jsonSelectedIDs;
    }

    //执行删除
    function deleteUserBy(ids) {
        var jsonSelectedIDs = new Array();

        $.each(ids, function (index, value) {
            if (typeof(value) != "undefined") {
                //组装参数
                jsonSelectedIDs.push({'id': value});
            }
            //console.log(index+"index" +value+"value");
        });

        var models = JSON.stringify(jsonSelectedIDs);
        $.ajax({
            url: 'sys/user-delete',
            data: 'models=' + models,
            type: 'post',
            success: function (data, textStatus, jqXHR) {
                if (data.code==200){
                    layer.msg('删除用户成功', {icon: 1});
                    layer.hide();
                    refreshFunction();
                }
                else {
                    layer.msg(data.data, {icon: 2});
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
            }
        });
    }

    //校验
    $(function () {
        $('#userSearchForm').bootstrapValidator({
            //live: 'disabled',
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                loginName: {
                    validators: {
                        regexp: {
                            regexp: /^[_a-zA-Z0-9-]+$/,
                            message: '不能输入中文和特殊字符'
                        }
                    }
                },
                userName: {
                    validators: {
                        regexp: {
                            regexp: /^[\u4e00-\u9fa5a-zA-Z·]+$/,
                            message: '不能输入数字和特殊字符'
                        }
                    }
                },
                email: {
                    validators: {
                        emailAddress: {
                            message: '邮箱格式不正确'
                        }
                    }
                }
            }
        });
    });
    /*]]>*/
</script>
